package generator.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import generator.domain.SysRole;
import generator.domain.SysUser;
import generator.service.SysRoleService;
import generator.service.SysUserService;
import generator.utis.Constants;
import generator.utis.PageSupport;
import generator.utis.UploadUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger log = Logger.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    //跳转到登录页面
    @RequestMapping("/toLogin")
    public String login(){
        return "login";
    }
    //登录
    @RequestMapping("/login")
    public String doLogin(
            @RequestParam(value = "account")String account,
            @RequestParam(value = "password")String password,
            HttpSession session,HttpServletRequest request){
        log.debug("登录方法");
        //调用service方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account);
        if (sysUser == null) {
            // 用户名不存在，直接返回错误信息
            request.setAttribute("error", "用户名不存在!");
            return "/login";
        }
        // 用户名存在，接下来验证密码
        if (sysUser.getPassword().equals(password)) { // 假设sysUser.getPassword()已经进行了适当的加密处理
            // 密码验证成功
            // 将登录用户放入session
            session.setAttribute(Constants.USER_SESSION, sysUser);
            // 登录成功，重定向到/user/toMain接口
            return "redirect:/user/toMain";
        } else {
            // 密码验证失败
            request.setAttribute("error", "密码输入错误!");
            return "/login";
        }
    }
    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION)== null){
            //重定向到登录页面接口
            return "redirect:/user/toLogin";
        }
        return "frame";
    }
//    @RequestMapping("/uploadImg")
//    public String fileUpload(){
//        return "/sysUser/update_file.jsp";
//    }
//    @RequestMapping("/doUpoadImg")
//    @ResponseBody
//    public String doUpoadImg(@RequestParam(value = "attach",required = false)MultipartFile attachs){
//        return FileUploadUtil.uploadImage(attachs);//返回url
//    }
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest request){
        request.setAttribute("e",e);
        return "error";
    }

    /**
     * 删除
     * @param userid
     * @return
     */
    @DeleteMapping("del/{userid}")
    @ResponseBody
    public String del(@PathVariable Long userid){
        JSONObject jsonObject = new JSONObject();
        SysUser sysUser = new SysUser();
        sysUser.setId(userid);
        sysUser.setStatus(false);
        Boolean b = sysUserService.updateById(sysUser);
        try{
            jsonObject.put("delResult",b.toString());
        }catch(Exception e){
            jsonObject.put("delResult","notexist");
        }
        return jsonObject.toJSONString();
    }
//    public String exLogin(@RequestParam String account,@RequestParam String password){
//        //调用service方法，进行用户匹配
//        SysUser user=sysUserService.login(account,password);
//        if (null==user) {//登录失败!
//            throw new RuntimeException("用户名或密码不正确,跳转到错误页面!");
//        }
//        return "redirect:/user/toMain";
//    }

    /**
     * 分页
     * @param model
     * @param queryRealName
     * @param queryRoleId
     * @param pageIndex
     * @return
     */
    @GetMapping("/list")
    public String getUserList(Model model,String queryRealName,Integer queryRoleId
        ,@RequestParam(defaultValue = "1") Integer pageIndex){
        List<SysUser> userList=null;
        try {
            //设置页面容量
            int pageSize=Constants.pageSize;
            //总数量(表)
            int totalCount=sysUserService.getUserCount(queryRealName,queryRoleId);
            //总页数
            PageSupport pages=new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount=pages.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex>totalPageCount){
                throw new RuntimeException("页码不正确");
            }
            userList=sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
            model.addAttribute("userList",userList);
            List<SysRole> roleList=null;
            roleList=sysRoleService.getRoleList();
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户列表接口访问失败!");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }
    //跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }

    /**
     * 跳转到添加页面
     * @param request
     * @return
     */
    @GetMapping(value = "/toAdd")
    public String toAdd(HttpServletRequest request){
        return "sysUser/add";
    }
//    @PostMapping("/add")
//    public String add(TSysUser sysUser, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs",required = false)MultipartFile[] attachs) {
//        String idPicPath = null;
//        String workPicPath = null;
//        String errorInfo = null;
//        boolean flag = true;
//        String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
//        log.info("uploadFile path ===================>"+path);
//        for (int i = 0; i < attachs.length; i++) {
//            MultipartFile attach = attachs[i];
//            if (!attach.isEmpty()){
//                if (i == 0){
//                    errorInfo = "uploadFileError";
//                }else if (i == 1){
//                    errorInfo = "uploadWpError";
//                }
//                String oIdFileName = attach.getOriginalFilename(); //原文件名
//                log.info("uploadFile oIdFileName ===================>"+oIdFileName);
//                String prefix = FilenameUtils.getExtension(oIdFileName);  //原文件后缀
//                log.debug("uploadFile prefix========================>"+prefix);
//                int filesize = 500000;
//                log.debug("uploadFile size =======================>"+attach.getSize());
//                if (attach.getSize() > filesize){
//                    request.setAttribute(errorInfo,"* 上传大小不得超过500K");
//                    flag = false;
//                }else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
//                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){
//                    String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
//                    log.debug("new fileName ==============" +attach.getName());
//                    File targetFile = new File(path);
//                    if (!targetFile.exists()){
//                        targetFile.mkdirs();
//                    }
//                    //保存
//                    try {
//                        attach.transferTo(new File(targetFile,fileName));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        request.setAttribute(errorInfo,"* 上传失败!");
//                        flag = false;
//                    }
//                    if (i == 0){
//                        idPicPath = File.separator+"statics"+File.separator
//                                +"uploadfiles"+File.separator+fileName;
//                    }else if (i == 1){
//                        workPicPath = File.separator+"statics"+File.separator
//                                +"uploadfiles"+File.separator+fileName;
//                    }
//                    log.debug("idPicPath:"+idPicPath);
//                    log.debug("workPicPath:"+workPicPath);
//                }else {
//                    request.setAttribute(errorInfo,"* 上传图片格式不正确");
//                    flag = false;
//                }
//            }
//        }
//        if (flag){
//            sysUser.setCreateduserid(((TSysUser)session.getAttribute(Constants.USER_SESSION)).getId());
//            sysUser.setIdpicpath(idPicPath);
//            sysUser.setWorkpicpath(workPicPath);
//            if (sysUserService.add(sysUser)){
//                return "redirect:/user/list";
//            }
//        }
//        return "sysUser/add";
//    }
    /**
     * 添加
     * @param sysUser
     * @param session
     * @return
     */
    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "attachs",required = false)MultipartFile[] attachs) throws IOException {
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("static" + File.separator + "uploadfiles");
        log.info("uploadFile path  ======================>" + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                    idPicPath = UploadUtil.uploadImage(attach);
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                    workPicPath = UploadUtil.uploadImage(attach);
                }
                /*String oldFileName = attach.getOriginalFilename();//原文件名
                log.info("uploadFile oIdFileName======================>" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件文件后缀
                log.debug("uploadFile prefix======================>" + prefix);
                int filesize = 5000000;
                log.debug("uploadFile filesize======================>" + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过500K
                    request.setAttribute(errorInfo, " * 上传文件大小不得超过500K");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传文件格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                    log.debug("new fileName======================>" + attach.getName());
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传文件失败");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = File.separator + "static" + File.separator
                                + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "static" + File.separator
                                + "uploadfiles" + File.separator + fileName;
                    }
                    log.debug("idPicPath======================>" + idPicPath);
                    log.debug("workPicPath======================>" + workPicPath);*/
            } else {
                request.setAttribute(errorInfo, " * 上传图片格式不正确");
                flag = false;
            }
        }
        if (flag) {
            sysUser.setCreateduserid(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            sysUser.setIdpicpath(idPicPath);
            sysUser.setWorkpicpath(workPicPath);
            if (sysUserService.add(sysUser)) {

                return "redirect:/user/list";
            }
        }
        return "sysUser/add";
    }

    /**
     * 详情
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/view/{id}")
    public String userview(@PathVariable Integer id,Model model){
        log.debug("根据id查询用户详情"+id);
        SysUser sysUser=sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    /**
     * 跳转修改
     * @param uid
     * @param model
     * @return
     */
    @GetMapping("/toUpdate")
    public String toUpdate(@RequestParam Integer uid,Model model){
        log.debug("跳转到修改用户信息页面");
        SysUser sysUser=sysUserService.getUserById(uid);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/update";
    }

    /**
     * 修改操作
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/update")
    public String modifySave(SysUser user,HttpSession session){
        user.setUpdateduserid(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.getUpdateUserId(user)){
            return "redirect:/user/list";
        }
        return "sysUser/update";
    }
    @GetMapping("/userExist")
    @ResponseBody
    public String userExist(String username){
        JSONObject jsonObject = new JSONObject();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",username);
        SysUser userServiceOne = sysUserService.getOne(queryWrapper);
        try{
            if (userServiceOne == null) {
                jsonObject.put("exist",0);
            }else {
                jsonObject.put("exist",1);
            }
        }catch(Exception e){
            jsonObject.put("exist",-1);
        }
        return jsonObject.toJSONString();
    }
}
